#include "itemManage.h"

void itemManageSyatem::loaddatabase(std::string location)
{
    std::fstream database(location);
    if(!database.is_open())
        return;
    databaselocation = location;
    int number = 0;
    database >> number;
    for(int i = 0;i<number;i++)
    {
        item middle;
        database >> middle.name;
        database >> middle.ID;
        database >> middle.price;
        database >> middle.number;
        items.emplace_back(middle);
    }
}

void itemManageSyatem::unloaddatabase()
{

    if(databaselocation.empty())
        return;
    std::fstream database(databaselocation);
    database << items.size() << "\n";
    for(item middle : items)
    {
        database << middle.name << " ";
        database << middle.ID << " ";
        database << middle.price << " ";
        database << middle.number << "\n";
    }
}

bool itemManageSyatem::additem(item target)
{
    if(items.size() == 0)
    {
        target.ID = std::to_string(0);
    }
    else target.ID = std::to_string(items.size() + 1);
    items.emplace_back(target);
    return 1;
}

bool itemManageSyatem::delitem(item *ptr)
{
    for(int i = 0;i< items.size(); i++)
    {
        if(items[i].ID == ptr->ID)
            items.erase(items.begin() + i);
    }
    return 1;
}

bool itemManageSyatem::finditem(std::string ID, item *&ptr)
{
    for(int i = 0;i<items.size();i++)
    {
        if(items[i].ID == ID)
        {
            ptr = &items[i];
            return 1;
        }
    }
    ptr = nullptr;
    return 0;
}

std::vector<item*> itemManageSyatem::gettarget(std::string name)
{
    std::vector<item*> middle;
    float confidence;
    for(int i = 0;i<items.size();i++)
    {
        if(findConfidence(name, items[i], confidence))
        {
            middle.emplace_back(&items[i]);
        }
    }
    return middle;
}

std::vector<item*> itemManageSyatem::gettarget(int maxinventory)
{
    std::vector<item*> middle;
    for(int i = 0;i<items.size();i++)
    {
        if(items[i].number < maxinventory)
        {
            middle.emplace_back(&items[i]);
        }
    }
    return middle;
}

bool findConfidence(std::string name, item target, float &confidence)
{
    const std::string& Name = target.name;
    
    // 计算字符串相似度
    int matchingChars = 0;
    for (std::size_t i = 0; i < name.length() && i < Name.length(); i++) 
    {
        if (name[i] == Name[i]) {
            matchingChars += 1;
        }
    }
    
    // 计算置信度
    float maxConfidence = static_cast<float>(std::min(name.length(), Name.length())) / std::max(name.length(), Name.length());
    confidence = static_cast<float>(matchingChars) / std::max(name.length(), Name.length());
    
    const float threshold = 0.01;
    return confidence >= threshold;
}